use anyhow::Result;
use sqlx::SqlitePool;
use std::path::Path;

use ftp_server::database::migrations;
use ftp_server::database::models::CreateUserRequest;
use ftp_server::services::UserService;

/// 初始化测试数据
pub struct TestDataInitializer {
    pool: SqlitePool,
}

impl TestDataInitializer {
    /// 创建新的测试数据初始化器
    pub async fn new(database_path: &str) -> Result<Self> {
        // 确保数据库目录存在
        if let Some(parent) = Path::new(database_path).parent() {
            std::fs::create_dir_all(parent)?;
        }
        
        // 连接数据库
        let database_url = format!("sqlite:{}", database_path);
        let pool = SqlitePool::connect(&database_url).await?;
        
        Ok(Self { pool })
    }
    
    /// 初始化数据库
    pub async fn init_database(&self) -> Result<()> {
        println!("🗄️ 初始化数据库...");
        
        // 运行数据库迁移
        migrations::run_migrations(&self.pool).await?;
        
        println!("✅ 数据库初始化完成");
        Ok(())
    }
    
    /// 创建测试用户
    pub async fn create_test_users(&self) -> Result<()> {
        println!("👤 创建测试用户...");
        
        let user_service = UserService::new(self.pool.clone());
        
        // 创建测试用户1
        let test_user1 = CreateUserRequest {
            username: "testuser".to_string(),
            password: "testpass".to_string(),
            home_directory: "/testuser".to_string(),
            max_storage_size: Some(1073741824), // 1GB
        };
        
        match user_service.create_user(&test_user1).await {
            Ok(user) => println!("✅ 创建用户: {} (ID: {})", user.username, user.id),
            Err(e) => println!("⚠️ 用户可能已存在: {}", e),
        }
        
        // 创建测试用户2
        let test_user2 = CreateUserRequest {
            username: "admin".to_string(),
            password: "adminpass".to_string(),
            home_directory: "/admin".to_string(),
            max_storage_size: Some(2147483648), // 2GB
        };
        
        match user_service.create_user(&test_user2).await {
            Ok(user) => println!("✅ 创建用户: {} (ID: {})", user.username, user.id),
            Err(e) => println!("⚠️ 用户可能已存在: {}", e),
        }
        
        // 创建只读用户
        let readonly_user = CreateUserRequest {
            username: "readonly".to_string(),
            password: "readonlypass".to_string(),
            home_directory: "/readonly".to_string(),
            max_storage_size: Some(536870912), // 512MB
        };
        
        match user_service.create_user(&readonly_user).await {
            Ok(user) => println!("✅ 创建用户: {} (ID: {})", user.username, user.id),
            Err(e) => println!("⚠️ 用户可能已存在: {}", e),
        }
        
        println!("✅ 测试用户创建完成");
        Ok(())
    }
    
    /// 创建测试目录结构
    pub async fn create_test_directories(&self) -> Result<()> {
        println!("📁 创建测试目录结构...");
        
        let test_dirs = vec![
            "data/files/testuser",
            "data/files/admin", 
            "data/files/readonly",
            "data/files/shared",
        ];
        
        for dir in test_dirs {
            if let Err(e) = std::fs::create_dir_all(dir) {
                println!("⚠️ 创建目录失败 {}: {}", dir, e);
            } else {
                println!("✅ 创建目录: {}", dir);
            }
        }
        
        // 创建一些测试文件
        let test_files = vec![
            ("data/files/testuser/test.txt", "Hello from testuser!"),
            ("data/files/admin/admin.txt", "Hello from admin!"),
            ("data/files/shared/shared.txt", "This is a shared file"),
        ];
        
        for (file_path, content) in test_files {
            if let Err(e) = std::fs::write(file_path, content) {
                println!("⚠️ 创建文件失败 {}: {}", file_path, e);
            } else {
                println!("✅ 创建文件: {}", file_path);
            }
        }
        
        println!("✅ 测试目录结构创建完成");
        Ok(())
    }
    
    /// 初始化所有测试数据
    pub async fn init_all(&self) -> Result<()> {
        println!("🚀 开始初始化测试数据");
        
        self.init_database().await?;
        self.create_test_users().await?;
        self.create_test_directories().await?;
        
        println!("🎉 测试数据初始化完成！");
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let initializer = TestDataInitializer::new("data/ftp_server.db").await?;
    initializer.init_all().await
}
